#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

// 在第一行、二行间插入一行
// 如果第二行已经插入过则覆盖
int main(int argc, char** argv)
{
	if (argc < 2)
	{
		printf("Usage: %s file\n", argv[0]);
		return -1;
	}

	int fd, lines = 0;
	off_t fsize;
	char* buf, *p, *sp = NULL, *ep = NULL;

	char msg[] = "/it's insert line\n";

	fd = open(argv[1], O_RDWR);
	if (fd == -1)
	{
		printf("open file failed, errno: %d\n", errno);
		return 1;
	}
	fsize = lseek(fd, 0, SEEK_END);

	buf = (char*)malloc(fsize);
	lseek(fd, 0, SEEK_SET);
	read(fd, buf, fsize);

	p = buf;
	while (*p) // 找到第二行首、第三行首
	{
		if (*p++ == '\n')
		{
			++lines;
			if (lines == 1)
				sp = p;
			else if (lines == 2)
				ep = p;
			else
				break;
		}
	}

	if (sp && ep)
	{
		//printf("%s\n", sp);
		//printf("%s\n", ep);

		//printf("sp - buf: %d\n", sp - buf);
		//printf("ep - sp: %d\n", ep - sp);
		//printf("buf + fsize - ep: %d\n", buf + fsize - ep);

		lseek(fd, 0, SEEK_SET);
		write(fd, buf, sp - buf);
		write(fd, msg, sizeof(msg) - 1); // 插入到第二行

		if (sp[0] != '/') // 根据需要修改判定条件
			write(fd, sp, buf + fsize - sp);
		else // 如果第二行是插入过的则跳过
			write(fd, ep, buf + fsize - ep);
	}

	close(fd);

	return 0;
}
